<?php

/**
 *    商品管理控制器
 */
class GoodsApp extends BackendApp
{

    var $_goods_mod;
    var $_placecate_mod;

    function __construct()
    {
        $this->GoodsApp();
    }

    function GoodsApp()
    {
        parent::BackendApp();

        $this->_goods_mod = & m('goods');
        $this->_placecate_mod = m("placecategory");
    }

    /* 商品列表 */

    function index()
    {
        $show_options = array(
            '0' => '待上架',
            '1' => '已上架',
            '2' => '已下架',
        );
        $feature_options = array(
            '0' => '否',
            '1' => '是',
        );
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'goods_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'g.goods_id',
                'name' => 'goods_id',
                'type' => 'int',
            ),
            array(
                'field' => 'store_name',
                'equal' => 'like',
            ),
            array(
                'field' => 'brand',
                'equal' => 'like',
            ),
            array(
                'field' => 'closed',
                'type' => 'int',
            ),
            array(
                'field' => 'if_show',
                'type' => 'int',
            ),
            array(
                'field' => 'is_feature',
                'type' => 'int',
            ),
            array(
                'field' => 'g.add_time',
                'name' => 'add_time_from',
                'equal' => '>=',
                'handler' => 'gmstr2time',
            ),
            array(
                'field' => 'g.add_time',
                'name' => 'add_time_to',
                'equal' => '<=',
                'handler' => 'gmstr2time_end',
            ),
            array(
                'field' => 'g.act_id',
                'name' => 'act_id',
                'equal' => '>=',
                'type' => 'int',
            )
        ));
        // 分类
        $cate_id = empty($_GET['cate_id']) ? 0 : intval($_GET['cate_id']);
        if ($cate_id > 0)
        {
            $cate_mod = & bm('gcategory');
            $cate_ids = $cate_mod->get_descendant_ids($cate_id);
            $conditions .= " AND g.cate_id" . db_create_in($cate_ids);
        }
        //场景分类
        $placecate_id = empty($_GET['placecate_id']) ? 0 : intval($_GET['placecate_id']);
        if ($placecate_id > 0)
        {
            $placecate_ids = $this->_placecate_mod->get_descendant_ids($placecate_id);
            $goods_ids = $this->_placecate_mod->get_goods_ids($placecate_ids);
            $conditions .= " AND g.goods_id" . db_create_in($goods_ids);
        }

        //更新排序
        if (isset($_GET['sort']) && isset($_GET['order']))
        {
            $sort = strtolower(trim($_GET['sort']));
            $order = strtolower(trim($_GET['order']));
            if (!in_array($order, array('asc', 'desc')))
            {
                $sort = 'goods_id';
                $order = 'desc';
            }
        }
        else
        {
            $sort = 'goods_id';
            $order = 'desc';
        }

        $page = $this->_get_page();
        $goods_list = $this->_goods_mod->get_list_by_admin(array(
            'conditions' => "1 = 1" . $conditions,
            'count' => true,
            'order' => "$sort $order",
            'limit' => $page['limit'],
        ));
        foreach ($goods_list as $key => $goods)
        {
            $goods_list[$key]['cate_name'] = $this->_goods_mod->format_cate_name($goods['cate_name']);
        }
        $this->assign('goods_list', $goods_list);

        $page['item_count'] = $this->_goods_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

        // 第一级分类
        $cate_mod = & bm('gcategory', array('_store_id' => 0));
        $this->assign('gcategories', $cate_mod->get_options(0, true));
        $this->assign('placecategories', $this->_get_options($this->_placecate_mod));
        $this->assign('show_options', $show_options);
        $this->assign('feature_options', $feature_options);
        $this->import_resource(array('script' => 'mlselection.js,inline_edit.js'));
        $this->assign('enable_radar', Conf::get('enable_radar'));
        $this->import_resource(array('script' => 'inline_edit.js,mlselection.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->display('goods.index.html');
    }

    /* 推荐商品到 */

    function recommend()
    {
        if (!IS_POST)
        {
            /* 取得推荐类型 */
            $recommend_mod = & bm('recommend', array('_store_id' => 0));
            $recommends = $recommend_mod->get_options();
            if (!$recommends)
            {
                $this->show_warning('no_recommends', 'go_back', 'javascript:history.go(-1);', 'set_recommend', 'index.php?app=recommend');
                return;
            }
            $this->assign('recommends', $recommends);
            $this->display('goods.batch.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $recom_id = empty($_POST['recom_id']) ? 0 : intval($_POST['recom_id']);
            if (!$recom_id)
            {
                $this->show_warning('recommend_required');
                return;
            }

            $ids = explode(',', $id);
            $recom_mod = & bm('recommend', array('_store_id' => 0));

            $recom_mod->createRelation('recommend_goods', $recom_id, $ids);
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $cache_server = & cache_server();
            $cache_server->delete('recommend');

            $this->admin_log(Lang::get('goods') . ':' . $id . Lang::get('recommend_to') . ':' . $recom_mod->get_fields_name($recom_id, 'recom_name'));
            $this->show_message('recommend_ok', 'back_list', 'index.php?app=goods&page=' . $ret_page, 'view_recommended_goods', 'index.php?app=recommend&amp;act=view_goods&amp;id=' . $recom_id);
        }
    }

    /* 编辑商品 */

    function edit()
    {
        if (!IS_POST)
        {
            $this->display('goods.batch.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $ids = explode(',', $id);
            $data = array();
            if (trim($_POST['brand']))
            {
                $data['brand'] = trim($_POST['brand']);
            }
            if ($_POST['closed'] >= 0)
            {
                $data['closed'] = $_POST['closed'] ? 1 : 0;
                $data['close_reason'] = $_POST['closed'] ? $_POST['close_reason'] : '';
            }
            if ($_POST['is_hot'] >= 0)
                $data['is_hot'] = $_POST['is_hot'];
            if ($_POST['if_show'] >= 0)
                $data['if_show'] = $_POST['if_show'];

            if (empty($data))
            {
                $this->show_warning('no_change_set');
                return;
            }

            $this->_goods_mod->edit($ids, $data);
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->admin_log(Lang::get('edit') . Lang::get('goods') . ':' . $id);
            $this->show_message('edit_ok', 'back_list', 'index.php?app=goods&page=' . $ret_page);
        }
    }
    
    function edit_category()
    {
        if (!IS_POST)
        {
            // 第一级分类
            $cate_mod = & bm('gcategory', array('_store_id' => 0));
            $this->assign('gcategories', $cate_mod->get_options(0, true));

            $this->headtag('<script type="text/javascript" src="{lib file=mlselection.js}"></script>');
            $this->display('goods.batch.cate.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }

            $ids = explode(',', $id);
            $data = array();
            if ($_POST['cate_id'] > 0)
            {
                $data['cate_id'] = $_POST['cate_id'];
                $data['cate_name'] = $_POST['cate_name'];
            }

            if (empty($data))
            {
                $this->show_warning('no_change_set');
                return;
            }

            $this->_goods_mod->edit($ids, $data);
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->admin_log(Lang::get('edit') . Lang::get('goods') . ':' . $id);
            $this->show_message('edit_ok', 'back_list', 'index.php?app=goods&page=' . $ret_page);
        }
    }

    //异步修改数据
    function ajax_col()
    {
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        $column = empty($_GET['column']) ? '' : trim($_GET['column']);
        $value = isset($_GET['value']) ? trim($_GET['value']) : '';
        $data = array();

        if (in_array($column, array('goods_name', 'brand', 'closed', 'is_hot', 'if_show', 'is_cheap')))
        {
            $data[$column] = $value;
            $this->_goods_mod->edit($id, $data);
            if (!$this->_goods_mod->has_error())
            {
                $info = $value ? "是" : "否";
                $this->admin_log(Lang::get('edit') . Lang::get('goods') . Lang::get($column) . ':' . $info . ':' . $id);
                echo ecm_json_encode(true);
            }
        }
        else
        {
            return;
        }
        return;
    }

    /* 删除商品 */

    function drop()
    {
        if (!IS_POST)
        {
            $this->display('goods.batch.html');
        }
        else
        {
            $id = isset($_POST['id']) ? trim($_POST['id']) : '';
            if (!$id)
            {
                $this->show_warning('Hacking Attempt');
                return;
            }
            $ids = explode(',', $id);

            // notify store owner
            $ms = & ms();
            $goods_list = $this->_goods_mod->find(array(
                "conditions" => $ids,
                "fields" => "goods_name, store_id",
            ));
            foreach ($goods_list as $goods)
            {
                //$content = sprintf(LANG::get('toseller_goods_droped_notify'), );
                $content = get_msg('toseller_goods_droped_notify', array('reason' => trim($_POST['drop_reason']),
                    'goods_name' => addslashes($goods['goods_name'])));
                $ms->pm->send(MSG_SYSTEM, $goods['store_id'], '', $content);
            }
            $this->admin_log(Lang::get('drop') . Lang::get('goods') . ':' . $id);

            // drop
            $this->_goods_mod->drop_data($ids);
            $this->_goods_mod->drop($ids);
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->show_message('drop_ok', 'back_list', 'index.php?app=goods&page=' . $ret_page);
        }
    }

    /*
     * 添加特色商品
     * @author libaoling
     * @time 2014-12-2
     */

    function ajax_add_feature()
    {
        $goods_id = empty($_GET['goods_id']) ? 0 : intval($_GET['goods_id']);
        $sort = empty($_GET['sort']) ? 0 : intval($_GET['sort']);
        $title = empty($_GET['title']) ? '' : trim($_GET['title']);

        if (!$goods_id)
        {
            echo json_encode(array('done' => false, 'msg' => "没有商品可设为特色商品"));
            return;
        }

        if (!$title)
        {
            echo json_encode(array('done' => false, 'msg' => '特色商品标题不可为空'));
            return;
        }

        $is_feature = $this->_goods_mod->getCol("select is_feature from wl_goods where goods_id = " . $goods_id);
        if ($is_feature[0])
        {
            echo json_encode(array('done' => false, 'msg' => '此商品已是特色商品'));
            return;
        }

        $data = array(
            'goods_id' => $goods_id,
            'add_time' => time(),
            'sort' => $sort,
            'title' => $title
        );

        if ($this->_goods_mod->edit($goods_id, array('is_feature' => 1)))
        {
            $feature_mod = m("features");
            $feature = $feature_mod->getCol("select goods_id from wl_features where goods_id = " . $goods_id);
            if ($feature[0])
            {
                unset($data['goods_id']);
                $feature_mod->edit($goods_id, $data);
            }
            else
                $feature_mod->add($data);
        }
        else
        {
            echo json_encode(array('done' => false, 'msg' => "设为特色商品失败"));
            return;
        }

        echo json_encode(array('done' => true, 'msg' => 'ok'));
        return;
    }

    function recommend_to_place()
    {
        $goods_id = empty($_GET['goods_id']) ? 0 : intval($_GET['goods_id']);
        if (!IS_POST)
        {
            // 第一级分类
            $categories = $this->_get_options($this->_placecate_mod);
            $selects = $this->_goods_mod->getRelatedData('belongs_to_placecategory', $goods_id);

            $this->assign("selects", $selects);
            $this->assign("categories", $categories);
            $this->headtag('<script type="text/javascript" src="{lib file=mlselection.js}"></script>');
            $this->display('placegoods.form.html');
        }
        else
        {
            $cate_ids = array_unique($_POST['cate_id']);
            if (!$cate_ids)
            {
                $this->show_warning('请选择场景分类');
                return;
            }

            $this->_goods_mod->unlinkRelation('belongs_to_placecategory', $goods_id);
            $this->_goods_mod->createRelation('belongs_to_placecategory', $goods_id, $cate_ids);
            $this->_placecate_mod->clear_cache();
            $ret_page = isset($_GET['ret_page']) ? intval($_GET['ret_page']) : 1;
            $this->admin_log('修改商品的场景分类:' . implode(',', $cate_ids));
            $this->show_message('修改商品场景分类成功', 'back_list', 'index.php?app=goods&page=' . $ret_page);
        }
    }

    function import_place()
    {
        if (!IS_POST)
        {
            // 第一级分类
            $categories = $this->_get_options($this->_placecate_mod);

            $this->assign("categories", $categories);
            $this->headtag('<script type="text/javascript" src="{lib file=mlselection.js}"></script>');
            $this->display('placegoods.import.html');
        }
        else
        {
            $cate_ids = array_unique($_POST['cate_id']);
            $goods_urls = $_POST['goods_urls'];
            if (!$cate_ids)
            {
                $this->show_warning('请选择场景分类');
                return;
            }
            if (!$goods_urls)
            {
                $this->show_warning('请添入要推荐的商品链接');
                return;
            }
            preg_match_all("#\d+#", $goods_urls, $matchs);
            $goods_ids = $matchs[0];
            if (!$goods_ids)
            {
                $this->show_warning('你添入的文本信息不正确');
                return;
            }

            foreach ($cate_ids as $cate_id)
            {
                $this->_placecate_mod->createRelation('has_goods', $cate_id, $goods_ids);
            }
            $this->_placecate_mod->clear_cache();
            $this->admin_log('批量导入商品到场景分类:cate_ids:' . implode(',', $cate_ids) . 'goods_ids:' . implode(",", $goods_ids));
            $this->show_message('修改商品场景分类成功', 'back_list', 'index.php?app=goods');
        }
    }

    function revoked_place_goods()
    {
        $placecate_id = empty($_GET['placecate_id']) ? 0 : intval($_GET['placecate_id']);
        $id = isset($_GET['id']) ? trim($_GET['id']) : '';
        if (!$placecate_id)
        {
            $this->show_warning('请先选择场景分类');
            return;
        }
        if (!$id)
        {
            $this->show_warning('请先选择商品id');
            return;
        }
        $ids = explode(',', $id);
        $placecate_ids = $this->_placecate_mod->get_descendant_ids($placecate_id);
        
        $sql = "DELETE FROM `wl_place_category_goods` WHERE cate_id " . db_create_in($placecate_ids) . " AND goods_id " . db_create_in($ids);
        $this->_goods_mod->db->query($sql);
        $this->_placecate_mod->clear_cache();
        $this->admin_log('批量撤销场景分类商品:cate_ids:' . implode(',', $placecate_ids) . 'goods_ids:' . implode(",", $ids));
        $this->show_message('撤销场景分类商品成功', 'back_list', 'index.php?app=goods&placecate_id='.$placecate_id);
        
    }

    private function _get_options($placecate_mod)
    {
        import('tree.lib');
        $tree = new Tree();
        $categories = $placecate_mod->get_list();
        $tree->setTree($categories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getOptions();
    }

}

?>
